﻿/*文件注释
 * ===============================================================================
 * 说明：
 * 作者：曾永佑
 * 版本：V1.0
 * 创建日期：2013-06-15
 * 完成日期： 
 * 修改纪录：  
 * ===============================================================================
 */  
        
using System;
using System.Text;
using System.Web;
using System.Web.Mvc; 
using System.Web.Script.Serialization;
using System.Collections.Generic;

namespace SRF.UI.View
{
    /// <summary>
    /// 
    /// </summary>
    public class TreeJsonResult<T> : ActionResult
    {
        string content = "";

        public TreeJsonResult(IList<T> list, Func<T, string> getId, Func<T, string> getPId, Func<T, string> getName, Action<T, IDictionary<string, object>> getAttrs = null)
        {
            string nodeFormat = "{{id:'{0}',pId:{1},name:'{2}'{3}}},";
            string pid, attrstr = "";

            if (list != null)
            {
                if (getId != null)
                {
                    foreach (T m in list)
                    {
                        pid = getPId(m);
                        if (string.IsNullOrEmpty(pid))
                        {
                            pid = "null";
                        }
                        else
                        {
                            pid = "'" + pid + "'";
                        }
                        if (getAttrs != null)
                        {
                            var attrs = new Dictionary<string, object>();
                            getAttrs(m, attrs);
                            attrstr = "";
                            foreach (KeyValuePair<string, object> kv in attrs)
                            {
                                attrstr += string.Format(",'{0}':'{1}'", kv.Key, kv.Value.ToString());
                            }
                        }
                        content += string.Format(nodeFormat, getId(m), pid, getName(m), attrstr);
                    }
                }
            }
             
            content = "[" + content.TrimEnd(',') + "]";
        }

        public Encoding ContentEncoding
        {
            get;
            set;
        }

        public string ContentType
        {
            get;
            set;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }

            response.Write(content);
        }
    }
}